# Christopher Callens
# list.py
# My "list" python parser
# April 11, 2011
#---------------------------

import ply.lex as lex
import sys

# Token names
tokens = (
	'NUMBER',
	'LPAREN',
	'RPAREN',
	'COMMA',
)

# Regular expression rules for simple tokens
t_LPAREN	= r'\('
t_RPAREN	= r'\)'
t_COMMA		= r','
t_NUMBER	= r'\d+'

# Line number tracker (TODO: See if this is really needed)
def t_newline(t):
	r'\n+'
	t.lexer.lineno += len(t.value)
	
# Characters to ignore
t_ignore = ' \t\n'

# Error handling
def t_error(t):
#	Not outputting this error right now
#	print "Illegal character '%s'" % t.value[0]
	t.lexer.skip(1)
	
# Build the lexer
lexer = lex.lex()

#######################################################

###YACC###

import ply.yacc as yacc

def printList(inputList):
	output = "( "
	if type(inputList)==type(list()):
		for l in inputList:
			output = output + printList(l) + ", "
	else:
		return inputList
	output = output[0:len(output)-2]
	return output + ")"

def p_top_list(p):
	'top : list'
	print printList(p[1])

def p_list_sequence(p):
	'list : LPAREN sequence RPAREN'
	newList = []
	if type(p[2])==type(list()):
		newList.extend(p[2])
	else:
		newList.append(p[2])
	p[0]=newList
	
def p_list_empty(p):
	'list : LPAREN RPAREN'
	p[0] = []
	
def p_sequence_sequence(p):
	'sequence : listelement COMMA sequence'
	sequenceList = [p[1]]
	sequenceList.extend(p[3])
	p[0]=sequenceList
	
def p_sequence_listelement(p):
	'sequence : listelement'
	p[0] = [p[1]]
	
def p_listelement_number(p):
	'listelement : NUMBER'
	p[0] = p[1]
	
def p_listelement_list(p):
	'listelement : list'
	p[0] = p[1]
	
# Error rule for syntax errors
def p_error(p):
	print "Syntax error in input!"
	
# Build the parser
parser = yacc.yacc()

try:
	print "Enter a list of numbers: "
	s = sys.stdin.read()
except EOFError:
	print ""
parser.parse(s)
